from PySide6.QtWidgets import QLabel, QWidget, QVBoxLayout, QLineEdit, QPushButton, QApplication


class MyWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Main Window")

        self.btnSetting = QPushButton("设置")

        self.labelFromSub = QLabel('From Sub Window')

        self.labelAccountText = "Account"
        self.labelPasswordText = "Password"

        self.labelAccount = QLabel(self.labelAccountText)
        self.labelPassword = QLabel(self.labelPasswordText)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.btnSetting)
        self.mainLayout.addWidget(self.labelAccount)
        self.mainLayout.addWidget(self.labelPassword)
        self.mainLayout.addWidget(self.labelFromSub)

        self.setLayout(self.mainLayout)

        self.resize(300, 300)

        self.bind()

    def bind(self):
        self.settingWindow = SettingWindow(self)
        self.btnSetting.clicked.connect(self.open_setting)

    def open_setting(self):
        self.settingWindow.show()

    def closeEvent(self, event):
        """
        在主窗口关闭时调用，关闭所有子窗口。
        """
        for child in QApplication.topLevelWidgets():
            if child is not self and isinstance(child, QWidget):
                child.close()
        event.accept()


class SettingWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__()
        self.parent = parent
        self.setWindowTitle("Setting Window")

        self.inputAccount = QLineEdit()
        self.inputPassword = QLineEdit()

        self.btnSubmit = QPushButton('确认')
        self.btnParent = QPushButton('Send To Parent')

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.inputAccount)
        self.mainLayout.addWidget(self.inputPassword)
        self.mainLayout.addWidget(self.btnSubmit)
        self.mainLayout.addWidget(self.btnParent)
        self.setLayout(self.mainLayout)

        self.resize(300, 300)

        self.btnSubmit.clicked.connect(self.save_setting)
        self.btnParent.clicked.connect(lambda: self.parent.labelFromSub.setText('这是由子窗口设置的内容'))

    def save_setting(self):
        self.parent.labelAccount.setText(self.parent.labelAccountText + ": " + self.inputAccount.text())
        self.parent.labelPassword.setText(self.parent.labelPasswordText + ": " + self.inputPassword.text())


if __name__ == '__main__':
    app = QApplication([])
    window = MyWindow()
    window.show()
    app.exec()
